package com.xu.commons.resovler;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;








import com.xu.commons.until.StringUtil;
import com.xu.commons.validate.Validator;
import com.xu.commons.validate.annotation.ValidateParam;
/**
 * 自定义方法参数解析器
 * @author xupeijiao
 *
 */
public class MethodArgumentResovler implements HandlerMethodArgumentResolver{
	public MethodArgumentResovler() {
		super();
	}
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		 if(parameter.hasParameterAnnotation(ValidateParam.class)){
			 return true;
		 }
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		ValidateParam validateParam=parameter.getParameterAnnotation(ValidateParam.class);
		String[] paramValues = webRequest.getParameterValues(parameter.getParameterName());
		Object value = null;
		if (paramValues != null) {
			value = paramValues.length == 1 ? paramValues[0] : paramValues;
		}
		/**
		 * 如果在request里面没有取到就去attribute里面拿
		 */
		if (value == null) {
			value = webRequest.getAttribute(parameter.getParameterName(), RequestAttributes.SCOPE_REQUEST);
		}
		Validator[] validators=null;
		String name=null;
		if (validateParam != null) {
			if (!StringUtil.isBlank(validateParam.name())) {
				 name=validateParam.name();
			}else{
				name=parameter.getParameterName();
			}
			 validators =validateParam.value();
		}
		validateValue(value,name,validators);
		/**
		 * 数据类型的强制转换
		 */
		if (binderFactory != null) {
			WebDataBinder binder = binderFactory.createBinder(webRequest, null, name);
			value = binder.convertIfNecessary(value, parameter.getParameterType(), parameter);
		}
		return value;
	}
	private void validateValue(Object value, String name, Validator[] validators) {
		for (int i = 0; i < validators.length; i++) {
			Validator validator =Validator.getValidator(validators[i]);
			if(validator!=null){
				if(value!=null&&!value.toString().trim().equals("")){
					validator.validate(name, value.toString());
				}else{
					if(validator.NOT_BLANK.equals(validator)){
						validator.validate(name, null);
					}
				}
			}
		}
		
	}

}
